

//@flow

/**
 * 封装带有请求超时的请求方法
 */
import { TIME_OUT_LONG } from "../config/config";
import { ResponseBaseModal } from "./modal/baseModal/responseBaseModal";
import { handleGetParams, handlePostParams, genId } from "../util/common";
import { TimeoutError } from "./modal/common/timeoutError";
import { RedirctError } from "./modal/common/redirectError";
import { RequestError } from "./modal/common/requestError";
import { ServerError } from "./modal/common/serverError";
import { UnknowError } from "./modal/common/unknowError";
import { ParseError } from "./modal/common/parseError";
import { ResponseKeyDefine } from "./business/responseKeyDefine";
import { RequestEmit } from "../container/requestAnalyzer/requestEmit";
import { DataProps } from "../container/requestAnalyzer/requestAnalyzer";

/**超时辅助函数 */
const TIME_OUT_ASSISSTANT = (paramPromise:Promise,time_out_long:number=TIME_OUT_LONG):Promise=>{
    let time_out_promise = new Promise((resolve,reject)=>{
        setTimeout(()=>{
            reject(TimeoutError)
        },time_out_long)
    })
    return Promise.race([time_out_promise,paramPromise]);
}
/**响应解析辅助函数 
 * 根据自身业务设置判断规则
 * 因为后台只会返回逻辑的状态码（0，1）等，表示操作成功与失败
 * 网络层面的问题自己定义
*/
const ResponseParseAssisstant =async function(res){
    try{
        if(res.status >= 200&&res.status<300){
            let resPromise = await res.json()
            let resModal:ResponseBaseModal = new ResponseBaseModal({
                code:resPromise[ResponseKeyDefine.STATUS_KEY],
                message:resPromise[ResponseKeyDefine.MESSAGE_KEY],
                data:resPromise
            })
            return Promise.resolve(resModal)
        }else if(res.status >=300 && res.status < 400){
            return Promise.resolve(new RedirctError(res))
        }else if(res.status >=400 && res.status <500){
            return Promise.resolve(new RequestError(res))
        }else if(res.status >=500 && res.status <600){
            return Promise.resolve(new ServerError(res))
        }else{
            return Promise.resolve(new UnknowError(res))
        }
    }catch(err){
        console.log(err)
        return Promise.resolve(new ParseError(res))
    }
}
/**请求类 */
export class Request {
    /**get方法 */
    static GET(url:string,params:Object,timeout:number=TIME_OUT_LONG):Promise<ResponseBaseModal>{
        /**插入捕获请求 */
        let guid : string = genId();
        let reqData : DataProps = {
            id : guid,
            reqUrl : `${url}?${handleGetParams(params)}`,
            method : 'get',
            params : params,
            status : 'process',
            header : null,
            response:null,
        }
        RequestEmit.RequestNoti(reqData)
        let req:Promise = fetch(reqData.reqUrl,{method:reqData.method}).then((res)=>{
            RequestEmit.ResponseBack({...reqData,response:res})
            return Promise.resolve(res)
        }).then(ResponseParseAssisstant)
        return TIME_OUT_ASSISSTANT(req,timeout)
    }
    /**post方法 */
    static POST(url:string,params:Object,header:Object,timeout:number=TIME_OUT_LONG):Promise<ResponseBaseModal>{
        let guid : string = genId();
        let reqData : DataProps = {
            id : guid,
            reqUrl : url,
            method : 'post',
            params : params,
            header : header,
            response:null,
            status : 'process',
        }
        RequestEmit.RequestNoti(reqData)
        let req :Promise = fetch(reqData.reqUrl,{method:reqData.method,body:handlePostParams(reqData.params),headers:reqData.header}).then(res=>{
            RequestEmit.ResponseBack({...reqData,response:res})
            return Promise.resolve(res)
        })
        return TIME_OUT_ASSISSTANT(req,timeout)
    }
}

